package com.fc.campusapplicationsystem.controller;

import com.fc.campusapplicationsystem.model.Comment;
import com.fc.campusapplicationsystem.model.Consumer;
import com.fc.campusapplicationsystem.service.CommentService;
import com.fc.campusapplicationsystem.util.ResponseOBJ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 贺哲
 * @2020-02-29 15:28
 */
@RestController
@RequestMapping("/commentController")
public class CommentController {

    @Autowired
    CommentService commentService;

    @GetMapping("/list")
    public ResponseOBJ<List<Comment>> list() {
        ResponseOBJ<List<Comment>> responseOBJ = ResponseOBJ.getInstance();
        try {
            List<Comment> comments = commentService.list();
            responseOBJ.setData(comments);
            responseOBJ.setMsg("查询成功");
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            responseOBJ.setMsg("查询失败");
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }

    /**
     * 获得对当前报修单的所有评论
     * @param reId
     * @return
     */
    @GetMapping("/getCommentByReListId")
    public ResponseOBJ<List<Comment>> getCommentByReListId(@RequestParam("reId") Integer reId){
        ResponseOBJ<List<Comment>> responseOBJ = ResponseOBJ.getInstance();
        try {
            List<Comment> comments = commentService.getCommentByReListId(reId);
            responseOBJ.setData(comments);
            responseOBJ.setMsg("查询成功");
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            responseOBJ.setMsg("查询失败");
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }


    /**
     * Comment:需要 reId（报修单ID），comments（评论内容）
     *
     * @param feedback
     * @return
     */
    @PostMapping("/add")
    public ResponseOBJ<Integer> add(@RequestBody Comment comment, HttpServletRequest request) {
        ResponseOBJ<Integer> responseOBJ = ResponseOBJ.getInstance();
        HttpSession session = request.getSession(true);
        Consumer consumer = (Consumer) session.getAttribute("consumer");
        comment.setUserId(consumer.getId());
        try {
            Integer result = commentService.add(comment);
            responseOBJ.setData(result);
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }
}
